package com.sc.common.algorithm;


import org.apache.commons.lang3.StringUtils;
import org.apache.shardingsphere.api.sharding.standard.PreciseShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.standard.PreciseShardingValue;
import org.joda.time.DateTime;
import java.util.Collection;

/**
 * 按月分表
 * 确分片算法类名称，用于=和IN
 */
public class TableShardingByMonthAlgorithm implements PreciseShardingAlgorithm<String> {


    @Override
    public String doSharding(Collection<String> collection, PreciseShardingValue<String> preciseShardingValue) {
        // 分片列
        String shardingColumnName = preciseShardingValue.getColumnName();

        // 分片列的值
        String shardingColumnValue = new DateTime(preciseShardingValue.getValue()).toString("yyyyMMddHHmmss");

        //需要分库的逻辑表
        String logicTableName = preciseShardingValue.getLogicTableName();

        if(StringUtils.isBlank(shardingColumnValue)){
            throw new UnsupportedOperationException("定位表失败：分片列["+shardingColumnName+"]对应的值为空！");
        }

        String result = logicTableName + "_" + DateTime.now().toString("yyyyMM");
        return result;
    }
}
